import { reloadAuthorized } from './Authorized'

export function getAuthority(str?: string): string | string[] {
  const authorityString =
    typeof str === 'undefined' && localStorage
      ? localStorage.getItem('tidb-dashboard-authority')
      : str
  // authorityString could be admin, "admin", ["admin"]
  let authority
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString)
    }
  } catch (e) {
    authority = authorityString
  }
  if (typeof authority === 'string') {
    return [authority]
  }
  // if (!authority) {
  //   return ['admin']
  // }
  return authority
}

export function setAuthority(authority: string | string[] | undefined): void {
  if (!authority) {
    return
  }
  const proAuthority = typeof authority === 'string' ? [authority] : authority
  localStorage.setItem('tidb-dashboard-authority', JSON.stringify(proAuthority))
  // auto reload
  reloadAuthorized()
}

//根据准入权限，判断是有权限
export function hasAuthority(
  authority: string | string[] | undefined
): boolean {
  //当前权限
  const currentAuthority = getAuthority()

  let hasAuthority = authority === null || authority == undefined

  // 数组处理
  if (Array.isArray(authority)) {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.some((item) => authority.includes(item))) {
        hasAuthority = true
      }
    } else if (authority.includes(currentAuthority)) {
      hasAuthority = true
    }
  }

  // string 处理
  if (typeof authority === 'string') {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.some((item) => authority === item)) {
        hasAuthority = true
      }
    } else if (authority === currentAuthority) {
      hasAuthority = true
    }
  }

  return hasAuthority
}
